<?php

namespace App\Http\Controllers;

use App\Events\OrderComputedDistribution;
use App\Jobs\AutoReceipt;
use App\Jobs\PaySuccessOrder;
use App\Models\Order;
use App\Service\ConfigService;
use App\User;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;

class PayNotifyController extends Controller
{
    /**
     * 订单支付成功  需要 增加商品销量，分销比例提成
     * 订单支付失败  需要 返回 对应的优惠券， 库存
     *
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function wechat()
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order = Order::where('order_sn', $message['out_trade_no'])->first();
            if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
                return true;
            }
            $extra = $order->extra;
            $order->extra = json_encode(array_merge($extra, $message));
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    // 获取用户id
                    $order->paid_at = now(); // 更新支付时间为当前时间
                    $order->ship_status = Order::SHIP_STATUS_PENDING;
                    $order->payment_sn = $message['transaction_id'];
                    // 下单成功
                    $config = app(ConfigService::class);
                    $paySuccessTemplate = $config->getPaymentSuccessTemplateMsg();
                    if ($paySuccessTemplate) {
                        // 发送通知
                        dispatch(new PaySuccessOrder($order, $extra['prepayid'], $paySuccessTemplate))->onQueue('successOrder');
                    }
                    // 获取确认时候时间
                    $shippedDay = $config->getAutoReceiptDay();
                    if (isset($message['attach'])) {
                        $data = json_decode($message['attach'], true);
                        $shared = User::find($data['member_id']);
                    } else {
                        $shared = null;
                    }
                    // 自动收货队列
                    dispatch(new AutoReceipt($order->id, $shippedDay, $shared))
                        ->delay(Carbon::parse($order->created_at)->addDays($shippedDay));
                } elseif (array_get($message, 'result_code') === 'FAIL') {  // 用户支付失败
                    $order->ship_status = Order::SHIP_STATUS_PAID_FAIL;
                    $order->updated_at = now();
                }
            } else {
                Log::info('订单回调失败', $message);
                return $fail('订单回调失败');
            }
            $order->save(); // 保存订单
            return true; // 返回处理完成
        });
        return $response;
    }
}
